package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.core.xml.StubObject;
import com.efounder.activity.AbActivity;
import com.efounder.activity.BaseMainHomeActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.FragmentChange;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.fragment.ChatListSwipeMenuFragment;
import com.efounder.chat.fragment.ContactsFragment;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.view.AddPopWindow;
import com.efounder.chat.view.CommonOtherPopWindow;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.interfaces.Ibadge;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.util.StorageUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.espcomp.PagerSlidingTabStrip;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

@Deprecated
public class PagerSlidingTabFragment extends BaseFragment implements
        OnClickListener {
    private boolean isViewCreated = false;
    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter adapter;


    private AbActivity activity;

    private ImageView menu_moreIV;


    /**
     * 二级菜单
     */
    private List<StubObject> mSecondLevelMenus; // 二级菜单


    ArrayList<String> TITLES = new ArrayList<String>();

    private String CAPTION = "caption";


    private StorageUtil storageUtil;

    /*
     * 设置信息初始化
     */
    private String port, service, address, path, APPID, sign;

    private String ServerURL;


//    private ImageLoader imageLoader;
//    private DisplayImageOptions options;

    private View rootView;
    private ImageView progressBar;
    RelativeLayout topLayout;

    private boolean isShowBackImage = false;//是否显示返回按钮
    private ImageView leftImageView;
    private StubObject rightTopLeftMenuObject;
    private ImageView ivRightTopLeft;
    private int firstShowItem=0;

    public PagerSlidingTabFragment() {
        super();
    }

    @SuppressLint({"NewApi", "ValidFragment"})
    public PagerSlidingTabFragment(List<StubObject> subMenus) {
        super();
        mSecondLevelMenus = subMenus;
        this.setAlone(false);
        if (mSecondLevelMenus != null) {
            for (Iterator<StubObject> it = mSecondLevelMenus.iterator(); it.hasNext();) {
                StubObject stubObject = it.next();
                Hashtable menuTable = stubObject.getStubTable();
                String parentID = (String) menuTable.get("_parentID");
                if (parentID != null && (parentID.equals("kaifa") || parentID.equals("shengchan")
                        || parentID.equals("kantan"))) {
                    isShowBackImage = true;
                }
                //stubObject中currentShow为1，那么显示这个fragment
                if ("1".equals(menuTable.get("currentShow"))) {
                    firstShowItem = mSecondLevelMenus.indexOf(stubObject);
                }
                //判断右上角左边那个按钮的菜单是否是主菜单（目前用于星际通讯通讯录的按钮）
                if (stubObject.getString("primaryMenu", "").equals("0")) {
                    //此菜单是右上角的菜单
                    rightTopLeftMenuObject = stubObject;
                    it.remove();
                }
            }
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (AbActivity) activity;
    }

    @SuppressWarnings("unchecked")
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_pager_sliding_tab,
                container, false);
        topLayout = (RelativeLayout) rootView.findViewById(R.id.tabs_ll);


        if (null != savedInstanceState) {
            mSecondLevelMenus = (List<StubObject>) savedInstanceState.getSerializable("databack");
        }

        MenuGnqxUtil.handleGNQX(mSecondLevelMenus);//处理功能权限

        if (null != mSecondLevelMenus && mSecondLevelMenus.size() > 0) {
            for (int i = 0; i < mSecondLevelMenus.size(); i++) {
                String cap = ((StubObject) mSecondLevelMenus.get(i)).getObject(
                        CAPTION, "").toString();
                TITLES.add(cap);
            }
        } else {
            TITLES.add("配置文件出错");
        }

        ivRightTopLeft = (ImageView) rootView.findViewById(R.id.iv_right_top_left);
        tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);

        tabs.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int position) {
                System.out.println("page==============" + position);
            }
        });
        pager = (ViewPager) rootView.findViewById(R.id.pager);
        //TODO 处理左侧图标
        leftImageView = (ImageView) rootView.findViewById(R.id.ttip);

        // fragment里面套嵌fragment 必须使用getchildfragmentmanager
        FragmentManager fm = getChildFragmentManager();
        fm.popBackStackImmediate(PagerSlidingTabFragment.class.getName(),
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
        adapter = new MyPagerAdapter(getChildFragmentManager());
        pager.setAdapter(adapter);
        pager.addOnPageChangeListener(onPageChangeListener);


        final int pageMargin = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                        .getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setIndicatorColor(Color.WHITE);

        tabs.setViewPager(pager);

        progressBar = (ImageView) rootView.findViewById(R.id.loadProgressBar);

        //获取progressBar设置图片的宽度和高度
        AnimationDrawable animationDrawable = (AnimationDrawable) progressBar.getBackground();

        animationDrawable.start();

        if (TITLES.size() == 1) {
//            RelativeLayout.LayoutParams progressBarparams = (RelativeLayout.LayoutParams) progressBar
//                    .getLayoutParams();
//            progressBarparams.rightMargin = 20;
//            progressBarparams.addRule(RelativeLayout.LEFT_OF, R.id.tabs);
//            progressBar.setLayoutParams(progressBarparams);
        } else {

            RelativeLayout.LayoutParams progressBarparams = (RelativeLayout.LayoutParams) progressBar
                    .getLayoutParams();
            // progressBarparams.rightMargin = 20;
//            progressBarparams.addRule(RelativeLayout.RIGHT_OF, R.id.ttip);
            progressBar.setLayoutParams(progressBarparams);


            android.widget.RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tabs
                    .getLayoutParams();
            // params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            params.addRule(RelativeLayout.LEFT_OF, R.id.menu_more);
            params.addRule(RelativeLayout.RIGHT_OF, R.id.user_icon_container);
            //fix 添加右侧按钮被遮挡无法点击的问题
            if(rightTopLeftMenuObject!=null){
                params.setMargins( SizeUtils.dp2px( 13 ),0,SizeUtils.dp2px( 30 ),0);
            }
            tabs.setLayoutParams(params); // 使layout更新


        }

        // initBadge();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);

        initMenuMore(rootView);
        changeTopRightButton(firstShowItem);
//        if(((BaseApp)getContext().getApplicationContext()).isSystemInited()){
//            initBadge();
//        }
        isViewCreated = true;
        initTopRightLeft();
        return rootView;

    }
    //初始化右上角左边的图标
    private void initTopRightLeft() {
        if (rightTopLeftMenuObject != null) {
            ivRightTopLeft.setVisibility(View.VISIBLE);
            ivRightTopLeft.setOnClickListener( new OnClickListener() {
                @Override
                public void onClick(View v) {
                    AbFragmentManager fragmentManager = new AbFragmentManager(getActivity());
                    try {
                        fragmentManager.startActivity(rightTopLeftMenuObject, 0, 0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1, sticky = true)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        initBadge();

    }

    private void initBadge() {
        if (null != mSecondLevelMenus && mSecondLevelMenus.size() > 0) {
            ViewGroup tabViews = tabs.getViewList();
            for (int i = 0; i < mSecondLevelMenus.size(); i++) {
                StubObject stubObject = mSecondLevelMenus.get(i);
                String id = stubObject.getString("id", "");
                String isShowBadge = stubObject.getString("showBadge", "false");
                if (isShowBadge.equals("true")) {
                    int unReadCount = BadgeUtil.getCount(id);
                    View v = tabViews.getChildAt(i);
                    if (v instanceof Ibadge) {
                        if (((Ibadge) v).getBadgeView() == null) {
                            BadgeView badgeView = new BadgeView(getContext(), v);
                            badgeView.setBadgeMargin(0, 0);
                            badgeView.setTextSize(13);

                            ((Ibadge) v).initBadgeView(badgeView);
                        }
                        ((Ibadge) v).setBadgeCount(unReadCount);
                    }

                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        boolean mustRefresh = event.isRefreshAll();
        ViewGroup tabViews = tabs.getViewList();
        for (int i = 0; i < mSecondLevelMenus.size(); i++) {

            StubObject stubObject = mSecondLevelMenus.get(i);

            String isShowBadge = stubObject.getString("showBadge", "false");
            if (!isShowBadge.equals("true")) {
                continue;
            }

            String id = (String) stubObject.getID();
            List chatIDs = BadgeUtil.badgeMap.get(id);
            if (!mustRefresh)
                if (!BadgeUtil.isNeedRefreshBadge(chatIDs, fromUserId, chatType)) continue;
            int unReadCount = BadgeUtil.getCount(id);

            View v = tabViews.getChildAt(i);

            if (!(v instanceof Ibadge)) {
                if (v instanceof ViewGroup)
                    v = ((ViewGroup) v).getChildAt(0);
            }
            if (v instanceof Ibadge) {
                if (((Ibadge) v).getBadgeView() == null) {
                    BadgeView badgeView = new BadgeView(getContext(), v);
                    badgeView.setBadgeMargin(0, 0);
                    badgeView.setTextSize(8);

                    ((Ibadge) v).initBadgeView(badgeView);
                }
                if (v instanceof Ibadge) {
                    ((Ibadge) v).setBadgeCount(unReadCount);
                }
            }
//            if (((Ibadge) v).getBadgeView() == null) {
//                BadgeView badgeView = new BadgeView(getContext(), v);
//                badgeView.setBadgeMargin(0, 0);
//                badgeView.setTextSize(13);
//
//                ((Ibadge) v).initBadgeView(badgeView);
//            }
//            if (tabViews.getChildAt(i) instanceof Ibadge) {
//                ((Ibadge) v).setBadgeCount(unReadCount);
//            }
        }
    }

    /**
     * 处理左侧图标
     *
     * @param
     */
    private void initLeftImageAndTitleView() {
        // leftImageView = (ImageView) rootView.findViewById(R.id.ttip);

        //是否隐藏标题栏
        for (int i = 0; i < mSecondLevelMenus.size(); i++) {
            String isHideTitle = ((StubObject) mSecondLevelMenus.get(i)).getObject(
                    "hideTitle", "").toString();
            if ("1".equals(isHideTitle)) {
                topLayout.setVisibility(View.GONE);
            }
        }

        if ("0".equals(EnvironmentVariable.getProperty("isShowLeftAvatar"))) {
            leftImageView.setVisibility(View.INVISIBLE);
            return;
        }

        if (isShowBackImage) {
            leftImageView.setVisibility(View.INVISIBLE);
            ImageView backImageView = (ImageView) rootView.findViewById(R.id.ttip_back);
            backImageView.setVisibility(View.VISIBLE);
            // backImageView.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.ef_title_view_back));
            backImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    getActivity().finish();
                }
            });
            return;
        }
        User user = null;
        try {
            user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user != null && leftImageView != null) {
//            imageLoader.displayImage(URLModifyDynamic.getInstance().replace(user.getAvatar()), leftImageView, options);
            LXGlideImageLoader.getInstance().showUserAvatar(getActivity(), leftImageView, user.getAvatar());
            leftImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (getActivity() != null && getActivity() instanceof BaseMainHomeActivity) {
                        if (((BaseMainHomeActivity) getActivity()).isAllowLeftDrawer()) {
                            activity.getDrawerLayout().openDrawer(Gravity.LEFT);
                        }
                        return;
                    }
                    activity.getDrawerLayout().openDrawer(Gravity.LEFT);
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initLeftImageAndTitleView();
    }

    private void initMenuMore(View rootView) {

        menu_moreIV = (ImageView) rootView.findViewById(R.id.menu_more);
        if (this.getRightButtonType() == null || this.getRightButtonType().equals("")) {
            menu_moreIV.setVisibility(View.GONE);
        } else {
            menu_moreIV.setVisibility(View.VISIBLE);

        }
        menu_moreIV.setOnClickListener(this);
        if ("import".equals(getRightButtonType())
                || "star_asset_wallet_change".equals(getRightButtonType())) {
            menu_moreIV.setImageDrawable(getResources().getDrawable(R.drawable.right_top_import_menu));
        } else if ("add".equals(getRightButtonType())) {
            menu_moreIV.setImageDrawable(getResources().getDrawable(R.drawable.main_activtiy_add_normal));
        } else {
            //读取配置的图标并展示
            String localImagePath = ResFileManager.IMAGE_DIR + "/" + getRightTopButtonICon();
            if (getRightTopButtonICon() == null || "".equals(getRightTopButtonICon())) {
                localImagePath = "";
            }
            LXGlideImageLoader.getInstance().displayImage(getActivity(), menu_moreIV, localImagePath, R.drawable.right_top_import_menu
                    , R.drawable.right_top_import_menu);
        }
        updateMoreMenuVisibile(0);
    }
    //更改右上角按钮图标，这个角标不是父类的是 每一个子菜单页面配置的
    private void changeTopRightButton(int position) {
        StubObject itemStubObject = mSecondLevelMenus.get(position);
        if (itemStubObject.getStubTable().containsKey("itemMenuType")) {
            String itemMenuType = itemStubObject.getString("itemMenuType", "");
            if ("import".equals(itemMenuType)
                    || "star_asset_wallet_change".equals(itemMenuType)) {
                menu_moreIV.setImageDrawable( JfResourceUtil.getSkinDrawable(R.drawable.right_top_import_menu));
            } else if ("add".equals(itemMenuType)) {
                menu_moreIV.setImageDrawable(JfResourceUtil.getSkinDrawable(R.drawable.main_activtiy_add_normal));
            } else {
                //读取配置的图标并展示
                String itemMenuIcon = itemStubObject.getString("itemMenuIcon", "");
                Object localImagePath = ResFileManager.IMAGE_DIR + "/" + itemMenuIcon;
                if ("".equals(itemMenuIcon)) {
                    localImagePath = JfResourceUtil.getSkinDrawable(R.drawable.right_top_import_menu);
                }
                LXGlideImageLoader.getInstance().displayImage(getActivity(), menu_moreIV, localImagePath, R.drawable.right_top_import_menu
                        , R.drawable.right_top_import_menu);
            }
            menu_moreIV.setOnClickListener(new TopRightOnclickListener(itemMenuType));
        }
    }
    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.menu_more) {
            if ("share".equals(getRightButtonType())) {
                int position1 = pager.getCurrentItem();

                StubObject stubObject = (StubObject) mSecondLevelMenus.get(position1);
                String forms = stubObject.getObject(
                        "forms", "").toString();
                String caption = stubObject.getObject(
                        "caption", "").toString();

			/*storageUtil = new StorageUtil(activity, "storage");
            port = storageUtil.getString("port");
			address = storageUtil.getString("address");
			path = storageUtil.getString("path");
			boolean isSafe = storageUtil.getBoolean("isSafe", true);
			String protocol = null;
			if (isSafe) {
				protocol = "https";
			}else {
				protocol = "http";
			}
			ServerURL = protocol + "://" + address + ":" + port + "/" + path;
			String url =  ServerURL+"/GWTMobilePlay.html?forms="+forms+"&contentView="+forms+".form1";*/

                storageUtil = new StorageUtil(this.getActivity(), "storage");
                String address = storageUtil.getString("address", "");
                String path = storageUtil.getString("path", "");
                String port = storageUtil.getString("port", "8080");
                boolean isSafe = storageUtil.getBoolean("isSafe", true);
                String protocol = null;
                if (isSafe) {
                    protocol = "https";
                } else {
                    protocol = "http";
                }
                ServerURL = protocol + "://" + address + "/" + path;

                String url = ServerURL + "/AndroidForm/" + forms + ".html";
                System.out.println("分享的网址" + url);
            /*Toast.makeText(activity, url,
                    Toast.LENGTH_SHORT).show();*/

                String imagePath = Environment.getExternalStorageDirectory().toString() + "/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID) +
                        "/res" + "/unzip_res" + "/Image" + "/ic_launcher.png";

            } else if ("add".equals(getRightButtonType())) {
                AddPopWindow addPopWindow = new AddPopWindow(activity);
                addPopWindow.showPopupWindow(menu_moreIV);
            } else {
                //todo 通用右上角菜单点击事件 业务界面自己处理 20180728
                int position = pager.getCurrentItem();
                StubObject stubObject = (StubObject) mSecondLevelMenus.get(position);
                EventBus.getDefault().post(new RightTopMenuClickEvent(menu_moreIV, stubObject));
            }
        }

    }

    public class MyPagerAdapter extends FragmentPagerAdapter {
        Map<Integer, Fragment> fragmentMap = new HashMap<Integer, Fragment>();
        private Fragment currentFragment;

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            currentFragment = (Fragment) object;
            super.setPrimaryItem(container, position, object);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES.get(position);
        }

        @Override
        public int getCount() {
            return TITLES.size();
        }

        @Override
        public Fragment getItem(int position) {
            BaseFragment frag = null;

            if (null != mSecondLevelMenus) {
                StubObject mainMenuItem = (StubObject) mSecondLevelMenus
                        .get(position);
                AbFragmentManager ab = new AbFragmentManager(PagerSlidingTabFragment.this.getActivity());

                frag = ab.getFragment(mainMenuItem);
                if (TITLES.size() > 1) {
                    frag.setAlone(false);
                } else {
                    frag.setAlone(true);
                }
                frag.setBadgeType(PagerSlidingTabFragment.this.getBadgeType());
                if (frag instanceof SimpleWebFragmentNoRefreshNoForms) {
                    ((SimpleWebFragmentNoRefreshNoForms) frag)
                            .setTitleVisible(false);
                    // ((SimpleWebFragmentNoRefreshNoForms)frag).setUserVisibleHint(true);
                }
//                else if (frag instanceof ChatListFragment) {
////                    PagerSlidingTabFragment.this.setFragmentType("Message");
//
//                    ((ChatListFragment) frag).setInitprogressDismiss(new ChatListFragment.InitprogressDismiss() {
//                        @Override
//                        public void trigger(boolean show) {
//                            if (show) {
//                                initnetprogressdismissHandler.sendEmptyMessage(1);
//                            } else {
//                                initnetprogressdismissHandler.sendEmptyMessage(0);
//                            }
//
//                        }
//                    });
//                    progressBar.setVisibility(View.VISIBLE);
//
//                }
                else if (frag instanceof ChatListSwipeMenuFragment) {//新组件的聊天列表
                    ((ChatListSwipeMenuFragment) frag).setInitprogressDismiss(new ChatListSwipeMenuFragment.InitprogressDismiss() {
                        @Override
                        public void trigger(boolean show) {
                            if (show) {
                                initnetprogressdismissHandler.sendEmptyMessage(1);
                            } else {
                                initnetprogressdismissHandler.sendEmptyMessage(0);
                            }

                        }
                    });
                    progressBar.setVisibility(View.VISIBLE);
                } else if (frag instanceof ContactsFragment) {

                }


            } else {
                // frag = new BaseFragment();
            }

            fragmentMap.put(position, frag);
            return frag;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            fragmentMap.remove(position);
            super.destroyItem(container, position, object);
        }

        public Fragment getFragment(int key) {
            return fragmentMap.get(key);
        }

        public Fragment getCurrentFragment() {
            return currentFragment;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (pager != null) {
            int position = pager.getCurrentItem();
            Fragment fragment = adapter.getFragment(position);
            StubObject menuItem = (StubObject) mSecondLevelMenus.get(position);
            // 缓存中的fragment前台显示时，如果是viewType="webView"，通知webView开始加载
            if (hidden) {
                if (isViewCreated && fragment instanceof BaseFragment) {
                    BaseFragment baseFragment = (BaseFragment) fragment;
                    baseFragment.onInvisible();
                }
            }
            if (!hidden) {
                if (isViewCreated && fragment instanceof BaseFragment) {
                    BaseFragment baseFragment = (BaseFragment) fragment;
                    baseFragment.onVisible();
                }
            }
        }

        //处理左上角头像
        initLeftImageAndTitleView();

        //给ViewPager的 当前显示的fragment派发 onHiddenChanged
        if (adapter != null) {
            Fragment currentFragment = adapter.getCurrentFragment();
            if (currentFragment != null) {
                currentFragment.onHiddenChanged(hidden);
            }
        }

        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        pager.removeOnPageChangeListener(onPageChangeListener);
    }

    @Override
    public void onDestroy() {
        isViewCreated = false;
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", (Serializable) mSecondLevelMenus);
    }

    public MyPagerAdapter getAdapter() {
        return adapter;
    }

    Handler initnetprogressdismissHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://隐藏
                    progressBar.setVisibility(View.INVISIBLE);
                    break;
                case 1://显示
                    progressBar.setVisibility(View.VISIBLE);
//                    DisplayImageOptions options1 = new DisplayImageOptions.Builder()
//                            .showImageOnLoading(R.drawable.default_useravatar)            //加载图片时的图片
//                            .showImageForEmptyUri(R.drawable.default_useravatar)         //没有图片资源时的默认图片
//                            .showImageOnFail(R.drawable.default_useravatar).build();          //加载失败时的图片
//                    imageLoader.displayImage("",leftImageView,options1);

                    break;
            }
            super.handleMessage(msg);
        }
    };
    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            updateMoreMenuVisibile(position);
            changeTopRightButton(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void updateMoreMenuVisibile(int position) {
        //
        EventBus.getDefault().post(new FragmentChange(position));
        StubObject stubObject = mSecondLevelMenus.get(pager.getCurrentItem());
        if (menu_moreIV == null) {
            return;
        }
        if (stubObject.getString("showRightTopButton", "1").equals("0")) {
            menu_moreIV.setVisibility(View.INVISIBLE);
        } else {
            menu_moreIV.setVisibility(View.VISIBLE);
        }
    }
    private class TopRightOnclickListener implements OnClickListener {
        private String menuType;

        public TopRightOnclickListener(String menuType) {
            this.menuType = menuType;
        }

        @Override
        public void onClick(View v) {
            if ("share".equals(menuType)) {
                int position1 = pager.getCurrentItem();

                StubObject stubObject = (StubObject) mSecondLevelMenus.get(position1);
                String forms = stubObject.getObject(
                        "forms", "").toString();
                String caption = stubObject.getObject(
                        "caption", "").toString();

                storageUtil = new StorageUtil(getActivity(), "storage");
                String address = storageUtil.getString("address", "");
                String path = storageUtil.getString("path", "");
                String port = storageUtil.getString("port", "8080");
                boolean isSafe = storageUtil.getBoolean("isSafe", true);
                String protocol = null;
                if (isSafe) {
                    protocol = "https";
                } else {
                    protocol = "http";
                }
                ServerURL = protocol + "://" + address + "/" + path;

                String url = ServerURL + "/AndroidForm/" + forms + ".html";
                System.out.println("分享的网址" + url);

                String imagePath = Environment.getExternalStorageDirectory().toString() + "/" + EnvironmentVariable.getProperty(KEY_SETTING_APPID) +
                        "/res" + "/unzip_res" + "/Image" + "/ic_launcher.png";

            } else if ("add".equals(menuType)) {
                AddPopWindow addPopWindow = new AddPopWindow(activity);
                addPopWindow.showPopupWindow(menu_moreIV);
            } else if ("import".equals(menuType)) {
                final CommonOtherPopWindow commonOtherPopWindow = new CommonOtherPopWindow(getActivity());
                commonOtherPopWindow.addMenuButton( ResStringUtil.getString(R.string.openplanet_title_import_fans), R.drawable.open_plant_import_fans)
                        .setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //给星际星球使用
                                try {
                                    String className = getResources().getString(R.string.pageslidetab_import_activity);
                                    Class class1 = Class.forName(className);
                                    Intent intent = new Intent(getActivity(), class1);
                                    //intent.putExtra("number", user.getName());
                                    intent.putExtra("number", EnvironmentVariable.getUserName());
                                    intent.putExtra("hasRightButton", "false");
                                    startActivity(intent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                commonOtherPopWindow.dismiss();
                            }
                        });
                commonOtherPopWindow.showPopupWindow(menu_moreIV);
            } else {
                //todo 通用右上角菜单点击事件 业务界面自己处理 20180728
                int position = pager.getCurrentItem();
                StubObject stubObject = (StubObject) mSecondLevelMenus.get(position);
                EventBus.getDefault().post(new RightTopMenuClickEvent(menu_moreIV, stubObject));
            }
        }
    }
}
